package com.wiz.weixin.controllor;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.wiz.weixin.VO.MemberVO;
import com.wiz.weixin.common.ResponseCode;
import com.wiz.weixin.manager.CommonManager;
import com.wiz.weixin.manager.TencentManager;
import com.wiz.weixin.service.MemberService;
import com.wiz.weixin.service.VerificationCodeService;
import com.wiz.weixin.tencent.VO.UserInfoVo;
import com.wiz.weixin.util.MD5Util;
import com.wiz.weixin.util.PageView;

/**
 * 会员
 * @author xxy
 *
 */
@Controller
@RequestMapping("/member")
public class MemberControllor {
	private transient final Logger log=LoggerFactory.getLogger(getClass());
	private Gson gson = new GsonBuilder().disableHtmlEscaping().create();
	@Resource
	private MemberService memberService;
	@Resource
	private CommonManager commonManager;
	@Resource
	private TencentManager tencentManager;
	@Resource
	private VerificationCodeService verificationCodeService;
	
	/**中转到注册页面*/
	@RequestMapping(value="/toRegister")
	public String toRegister(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value = "param", required = true) String param,//站点id
//			@RequestParam(value = "rand", required = true) String rand,//rand
			HttpSession session, Model model) {
		
		
		String openid ="ovNRGs8IVk3ctBk5YLcxE45XG50g";//(String) Constant.map.get(rand);
		
		session.setAttribute("openid", openid);
		System.out.println("注册openid=========>"+openid);
		if(openid == null || openid.equals("")){
			model.addAttribute("msg", "验证失败，请重新扫码");
			return "/member/erro";
		}
		request.setAttribute("stationId",param);
		return "/member/register";
		
	}
	/**生成验证码*/
	@RequestMapping(value="/generateCode")
	@ResponseBody
	public String generateCode(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value = "phoneNum", required = true) String phoneNum,//手机号码
			@RequestParam(value = "stationId", required = true) String stationId,//站点id
    		HttpSession session, Model model) {
		int code = 0;
		try {
			Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$"); 
			Matcher m = p.matcher(phoneNum); 
			if(!m.matches()){
				new Exception("手机号码格式不正确！");
			}
			code =verificationCodeService.sendCode(phoneNum,stationId);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("phoneNum:"+phoneNum);
			log.error("generateCode:"+e.getMessage());
			return ResponseCode.DATA_ERROR;
		}
		
		return "{\"code\":200, \"msg\" : "+code+"}";
		
	}
	
	/**注册会员*/
	@RequestMapping(value="/register")
	public String register(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value = "stationId", required = true) String stationId,//站点id
			@RequestParam(value = "name", required = true) String name,//会员名称
			@RequestParam(value = "phoneNum", required = true) String phoneNum,//手机号码
			@RequestParam(value = "authCode", required = true) int authCode,//验证码
			@RequestParam(value = "idCard", required = false) String idCard,//身份证
			@RequestParam(value = "licensePlate", required = false) String licensePlate,//车牌
			@RequestParam(value = "fuellingPassword", required = false) String fuellingPw,//加油密码
			HttpSession session, Model model) {
		String openId = (String) session.getAttribute("openid");
		MemberVO member = new MemberVO(null,name, stationId, MD5Util.encode(fuellingPw), licensePlate, idCard,phoneNum,openId);
		
		try {
			String agent=request.getHeader("User-Agent").toLowerCase();
            if(!agent.contains("micromessenger")){
            	throw new Exception("请使用微信自带的浏览注册！");
            }
			if(openId == null || openId.equals("")){
				throw new Exception("不能得到你的微信编码！");
			}
			String result = memberService.register(member,authCode);
			UserInfoVo userInfoVo =  commonManager.getUserInfo(openId);
			model.addAttribute("userInfo", userInfoVo);
			model.addAttribute("member", member);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("phoneNum:"+phoneNum);
			log.error("register:"+e.getMessage());
			model.addAttribute("msg", e.getMessage());
			return "/member/erro";
		}
		return "/member/success";
	}
	/**账户余额列表*/
	@RequestMapping(value="/listAccount")
    public String listAccount(HttpServletRequest request,HttpServletResponse response,
    		HttpSession session, Model model) {
		
		List<MemberVO> list = null;
		String code = request.getParameter("code");
		try {
			String openid = (String) session.getAttribute("openid");
			if(openid == null || openid.equals("")){
				openid = tencentManager.getOpenId(code);
				session.setAttribute("openid", openid);
			}
			list = memberService.listMemberByOpenId(openid);
			
			model.addAttribute("list", list);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return "/member/listAccount";
		
	}
	/**
	 * 跳转会员收支明细
	 */
	@RequestMapping(value="/toDetail", method=RequestMethod.POST)
	public String toDetail(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value = "hqId", required = true) String hqId,//总部id
			@RequestParam(value = "memberId", required = true) String memberId,//站点id
			@RequestParam(value = "hqName", required = true) String hqName,//
			HttpSession session, Model model) throws UnsupportedEncodingException {
		request.setCharacterEncoding("UTF-8");  
		response.setCharacterEncoding("UTF-8"); 
		model.addAttribute("hqId", hqId);
		model.addAttribute("memberId", memberId);
		model.addAttribute("hqName", hqName);
		return "/member/detail";
		
	}
	/***
	 * 会员收支明细列表
	 */
	@RequestMapping(value="/details", method=RequestMethod.POST)
	@ResponseBody
	public String details(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value = "hqId", required = true) String hqId,//总部id
			@RequestParam(value = "memberId", required = true) String memberId,//站点id
			@RequestParam(value = "pageNo", required = false,defaultValue="1") int pageNo,//当前页
			@RequestParam(value = "pageSize", required = false,defaultValue="10") int pageSize,//每页显示几条记录
			HttpSession session, Model model) throws UnsupportedEncodingException {
		 request.setCharacterEncoding("UTF-8");  
	     response.setCharacterEncoding("UTF-8"); 
	     PageView pageView = new PageView(pageSize, pageNo);
		try {
			pageView = memberService.listAmountHistory(hqId,memberId,pageView);//"10005","10005114317863"
			pageView.setCode(200);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return gson.toJson(pageView);
		
	}
	
}
